var StoryPointer = window.StoryPointer || {};
var socket;
var utils = StoryPointer.Utils;
StoryPointer.Stories = {};
StoryPointer.Jira = {};
StoryPointer.User = {};
StoryPointer.Viewer = (function(window, document){

    var receiveUpdate = function() {
        socket.on("sendScore", function(data){
            saveUpdate(data);
	        updateTiles(data);
        });
    };

    var receiveAll = function() {
        socket.on("sendAll", function(stories){
            StoryPointer.Stories = stories;
        });
    };

    var updateJira = function(){
        $("#sendJira").click(function(){
            var jira = $(".inputJira").val(); //Temp
            var data = { "jira" : jira };

            saveJira(data);
            sendJira();

            return false;
        }.bind(this));
    };

	var updateTiles = function(data) {
		if(utils.isDataValid(data)){
			var selector = "#" + data.name;
			var scoreTile = $(selector);

			if(scoreTile.length > 0){
				scoreTile.children(".score").html(data.score);
			} else {
				$.get('/templates/tile.html', function(template){
					var scoreCards = $(".scoreCards ul");
					var insert = $(template);

					insert.attr("id", data.name);
					insert.children(".name").html(data.name);
					insert.children(".score").html(data.score);

					insert.appendTo(scoreCards);
				});
			}
		}
	}

	var saveUpdate = function(data) {
		if(utils.isDataValid(data)){
			if(StoryPointer.Stories[data.jira] != undefined){
				StoryPointer.Stories[data.jira][data.name] = data.score;
			} else {
				console.log("No such Jira");
			}
		}
	};

    var saveJira = function(data) {
        if(utils.isJiraValid(data)) {
            StoryPointer.Jira = data;
        }
    };

    var sendJira = function(){
        socket.emit("sendJira", StoryPointer.Jira);
    };

    var loadConfig = function(){

        $.ajax({
            dataType: "json",
            url: "/config.json",
            data: {},
            async:false,
            success: function(response){
                StoryPointer.config = response;
            }
        });

        socket = io.connect(StoryPointer.config.server+':'+StoryPointer.config.port);
    };

    var checkLoggedIn = function(){
        if(StoryPointer.User.username){
            $("#loginBox").hide();
            $("#dashboard").show();
            $(".userinfo .username").text(StoryPointer.User.userData.displayName);
        }else{
            $("#loginBox").show();
            $("#dashboard").hide();
            $(".userinfo .username").empty();
        }
    };

    var login = function(){

        $("#login").click(function(){
            StoryPointer.User.username = $("input[name=user]").val();
            StoryPointer.User.password = $("input[name=password]").val();

            StoryPointer.User.authtoken = btoa(StoryPointer.User.username + ":" + StoryPointer.User.password);

            socket.emit("loginUser", StoryPointer.User);

            socket.on("authenticated", function(data){

                StoryPointer.User.userData = $.parseJSON(data);

                checkLoggedIn();
            });

        });
    };



    var logout = function(){

        $("#logout").click(function(){
            StoryPointer.User.username = undefined;
            $("input[name=user]").val("");
            StoryPointer.User.password = undefined;
            $("input[name=password]").val("");
            checkLoggedIn();
        });
    };

    var init = function(){
        $(function(){
            loadConfig();
            checkLoggedIn();
            login();
            logout();
            updateJira();
            receiveAll();
            receiveUpdate();
        });
    };

    init();

})(window, document);

